/*
 * Copyright 2008-2009 ArtisanLogic.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.artisanlogic.io;

import java.io.Closeable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

// =====================================================================================================================
// ClosingStreamTemplate.java                                                                    Created on Feb 19, 2009
// ---------------------------------------------------------------------------------------------------------------------
/**
 * An implementation of StreamTemplate that ensures the provided StreamTask's stream is closed at the end of the process
 * regardless of whether or not the StreamTask completes successfully or throws an error.
 * 
 * @author sean@artisanlogic.com
 * @since 0.9-Beta
 */
// =====================================================================================================================
public class ClosingStreamTemplate<StreamType extends Closeable> implements StreamTemplate<StreamType> {

  // -------------------------------------------------------------------------------------------------------------------
  // private instance fields
  // -------------------------------------------------------------------------------------------------------------------
  
  private Log logger = LogFactory.getLog(getClass());
  
  // -------------------------------------------------------------------------------------------------------------------
  // public instance methods
  // -------------------------------------------------------------------------------------------------------------------
  
  /**
   * This implementation ensures the provided task's stream is closed.
   * 
   * @see com.artisanlogic.io.StreamTemplate#withStream(com.artisanlogic.io.StreamTask)
   */
  public void withStream(StreamTask<StreamType> task) throws RuntimeException {
    StreamType stream = null;
    try {
      stream = task.getStream();
      task.execute(stream);
    } catch(RuntimeException ex) {
      logger.error(ex, ex);
      throw ex;
    } catch(Exception ex) {
      logger.error(ex, ex);
      throw new RuntimeException(ex);
    } finally {
      try {
        if(stream != null) {
          stream.close();
        }
      } catch(Exception ex) {
        logger.error("The stream could not be properly closed.", ex);
      }
    }
  }

}
